package com.steakliu.event.order.service;

import com.steakliu.event.order.dto.MessageDTO;
import com.steakliu.event.order.dto.OrderDTO;
import com.steakliu.event.order.dto.StockDTO;
import com.steakliu.event.order.dto.UserDTO;
import com.steakliu.event.order.event.MessageEvent;
import com.steakliu.event.order.event.StockEvent;
import com.steakliu.event.order.event.UserEvent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 功能说明：订单Service
 *
 * <p>
 * Original @Author: steakliu-刘牌, 2022-06-25  19:52
 * <p>
 * Copyright (C)2020-2022  小四的技术之旅 All rights reserved.
 */
@Component
@Slf4j
@AllArgsConstructor
public class OrderService {

    private ApplicationEventPublisher applicationEventPublisher;

    public void placeOrder(OrderDTO orderDTO){
        log.info("=======开始下单操作=======");
        //保存订单
        this.saveOrder(orderDTO);

        //扣减库存
        StockDTO stockDTO = new StockDTO().setCommodityId(orderDTO.getCommodityId()).setNum(orderDTO.getNum());
        applicationEventPublisher.publishEvent(new StockEvent(stockDTO));

        //扣减余额
        UserDTO userDTO = new UserDTO().setUserId(orderDTO.getUserId()).setMoney(orderDTO.getPrice().multiply(new BigDecimal(orderDTO.getNum())));
        applicationEventPublisher.publishEvent(new UserEvent(userDTO));

        //短信通知
        MessageDTO messageDTO = new MessageDTO().setTel(orderDTO.getTel());
        applicationEventPublisher.publishEvent(new MessageEvent(messageDTO));

    }

    private void saveOrder(OrderDTO orderDTO){
        log.info("保存订单：【{}】",orderDTO);
    }
}
